/**
 * @FileName: JDKProxyFactory.java
 * @Package: com.ziroom.sms.std.rpc.proxyfacotry
 * @author liusq23
 * @created 2017/6/15 上午9:40
 * <p>
 * Copyright 2015 ziroom
 */
package com.ziroom.sms.std.rpc.proxyfacotry;

import com.ziroom.sms.std.rpc.*;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * <p></p>
 * <p>
 * <PRE>
 * <BR>	修改记录
 * <BR>-----------------------------------------------
 * <BR>	修改日期			修改人			修改内容
 * </PRE>
 *
 * @author liusq23
 * @version 1.0
 * @since 1.0
 */
public class JDKProxyFactory implements ProxyFactory {


    public <T> T getProxy(Class<?>[] interfaces,InvokerInvocationHandler invokerInvocationHandler) {
        return (T)Proxy.newProxyInstance(interfaces[0].getClassLoader(),interfaces,invokerInvocationHandler);
    }

    @Override
    public <T> Invoker<T> getInvoker(final T proxy,final Class<T> type) {
        return new Invoker<T>() {
            @Override
            public Class<T> getInterface() {
                return type;
            }

            @Override
            public Object invoke(Invocation invocation) throws RPCException {
                try {
                    String methodName = invocation.methodName();
                    Method method = type.getMethod(methodName,invocation.parameterTypes());
                    return method.invoke(proxy,invocation.getParameters());
                }catch (Exception e){
                    throw new RPCException(e);
                }
            }
        };
    }
}
